<template>
	<view style="height: calc( 100vh - 44px ); width: 160vw;">

		<navBarPopup style="" ref="navBarPopupRef" :pageData="pageData" @success="navChange" @close="navClose"></navBarPopup>

		<div class="scrollWrap" style="overflow: hidden; height:100%; width: 100vw; float: left; ">

			<div class="mask" @click="hideNav" v-if="showMask" style=""></div>

			<scroll-view scroll-y="true" style="height: calc( 100vh - 44px ); " :scroll-top="scrollTop"
				@scroll="onScroll">
				<view class="pageBox">
					<view class="desc" :style="{fontSize: arraySize[index] + 'px'}">
						<view class="item" v-if="pageData.publishDept">
							<text class="text1">【制定机关】</text>
							<text class="text2">{{pageData.publishDept}}</text>
						</view>
						<view class="item" v-if="pageData.publishWordSize">

							<text class="text1">【发布字号】</text>
							<text class="text2">{{pageData.publishWordSize}}</text>
						</view>
						<view class="item" style="" v-if="pageData.publishDate">

							<text class="text1">【发布时间】</text>
							<text class="text2">{{pageData.publishDate}}</text>

						</view>
						<view class="item" v-if="pageData.putDate">
							<text class="text1">【实施时间】</text>
							<text class="text2">{{pageData.putDate}}</text>
						</view>
						<view class="item" v-if="pageData.abolishDate">
							<text class="text1">【废止时间】</text>
							<text class="text2">{{pageData.abolishDate || '-'}}</text>
						</view>
					</view>
					<view class="content" :style="{fontSize: arraySize[index] + 'px', 'text-align': 'justify'}">
						<view v-for="(item, index) in pageData.chapterList" :key="index"
							:class="'itemIndex' + item.sort">
							<view class="item " ref="articleDiv" v-html="item.data"
								:class="{'active': item.checked == 1}" @touchstart="touchstart(item)"
								@touchend="touchend" :id="'itemId' + item.sort" :ref="'itemId' + item.sort"></view>
						</view>
					</view>
				</view>
			</scroll-view>
		</div>


		<uni-fab style="z-index: 9;" :pattern="pattern" :content="content" :horizontal="horizontal" :vertical="vertical"
			direction="horizontal" @trigger="trigger"></uni-fab>



		<tapLongPopup ref="tapLongPopupRef" @success="onTapLong" @cancel="onCancel"></tapLongPopup>

		<uni-popup ref="popupTextSize" class="navBarPup2" type="center" style="width: 60%;">
			<view class="pageBox2">
				<view class="item" v-for="(item, i) in array" @click="setTextSize(i)" :class="{'active': i == index}">
					{{item}}
				</view>
			</view>
		</uni-popup>

		<imagePreview ref="imagePreview"></imagePreview>
	</view>
</template>
<script>
	// https://juejin.cn/post/7171313957142003749
	import {
		APIJS
	} from '../../api/api.js'
	import {
		goLogin
	} from '@/utils/utils.js'
	import tapLongPopup from './tapLongPopup.vue'
	import Speech from 'speak-tts'
	import navBarPopup from './navBarPopup.vue'
	import imagePreview from './imagePreview.vue'
	export default {
		components: {
			navBarPopup,
			tapLongPopup,
			imagePreview
		},
		data() {
			return {
				scrollTop: 0, // 初始化滑动高度
				scrollToped: 0, // 已经滑动的高度
				goodsId: '',
				pageData: {},
				index: 1,
				array: ['小号', '默认', '中号', '大号'],
				arraySize: ['14', '16', '18', '22'],
				bookId: null,

				showMask: false,

				horizontal: 'right',
				vertical: 'bottom',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#39A6FF',
					buttonColor: '#39A6FF',
					iconColor: '#fff'
				},
				content: [{
						iconPath: '../../static/home1.png',
						selectedIconPath: '../../static/home1_1.png',
						text: '首页',
						active: false
					}, {
						iconPath: '../../static/font.png',
						selectedIconPath: '../../static/font.png',
						text: '字体',
						active: false
					},
					{
						iconPath: '../../static/star1.png',
						selectedIconPath: '../../static/star1_1.png',
						text: '加入书签',
						active: false
					},
				],


				speakStatus: 0, // 0 空闲中，可以播放，1，播放中，可以暂停 取消  2，已暂停，
				speech: null,
				handleData: {},
				timer: null,
				navShow: 0,
			}
		},

		watch: {
			// $route(newVal, oldVal) {
			// 	let detailScroll = uni.getStorageSync('detailScroll');
			// 	if (newVal.query.navShow != 1 && detailScroll) {
			// 		setTimeout(() => {
			// 			this.navChange(detailScroll)
			// 		}, 500)
			// 	}
			// }
		},

    onShow() {
			let detailScroll = uni.getStorageSync('detailScroll');
			if (detailScroll) {
				setTimeout(() => {
					this.navChange(detailScroll)
				}, 500)
			}
		},
		onLoad(opition) {
			let vm = this
			console.log(opition, 1111111111)

			// uni.$on('update', this.handleRouteUpdate);

			if (opition.bookId) {
				vm.bookId = opition.bookId
			}
			vm.navShow = opition.navShow || 0
			if (vm.navShow == 1) {
				setTimeout(() => {
					vm.showMask = true
					vm.$refs.navBarPopupRef.init()
				}, 200)
			}

			vm.goodsId = opition.id || '1'
			uni.showLoading({
				title: '加载中'
			});
			APIJS.getStandardContentById({
				id: vm.goodsId
			}).then((res) => {
				vm.pageData = res.data
				uni.hideLoading();

				if (res.data.bookContentStatus == 1) {
					vm.content[2].active = true
					vm.content[2].text = '删除书签'
				}

				if (res.data.bookId) {
					vm.bookId = res.data.bookId
				}


				// pageData.title
				uni.setNavigationBarTitle({
					title: vm.pageData.title
				});

				vm.pageData.chapterList = res.data.chapterList.map((row) => {
					return {
						...row,
						checked: 0
					}
				})

				vm.index = uni.getStorageSync('fontSizeIndex') || 0
				console.log(vm.bookId, vm.navShow, 'vm.navShow')
				if (vm.bookId && vm.navShow == 0) {
					// vm.bookId = vm.bookId
					// 书签详情
					APIJS.getBookmarkDetail({
						id: vm.bookId
					}).then((res) => {

						if (res.data?.scrollInfo) {
							vm.scrollTop = res.data?.scrollInfo
						}

					})
				}
			}).catch((e) => {
				uni.hideLoading();
				setTimeout(() => {
					goLogin(`/pages/detail/detail?id=${vm.goodsId}`)
				}, 600)
			})

			setTimeout(() => {
				// #ifdef H5
				const image = this.$el.querySelectorAll('.content img');
				if (image.length > 0) {
					// image.addEventListener('click', this.articleClick);  
					image.forEach((img, index) => {
						img.addEventListener('click', this.articleClick);
					});
				}
				// #endif
			}, 1000)

		},

		beforeDestroy() {
			// #ifdef H5
			const image = this.$el.querySelectorAll('img');
			if (image.length > 0) {
				image.forEach((img, index) => {
					img.removeEventListener('click', this.articleClick);
				});
			}
			// #endif
		},
		// onNavigationBarButtonTap(e) {
		// 	console.log(e , 1111)
		//     if (e.index === 0) {
		//       // 这里的0是指返回按钮的索引，通常标题左边第一个按钮是返回按钮
		//       // 可以在这里编写返回事件的逻辑
		//       uni.navigateBack(); // 如果需要返回上一页，可以调用这个方法
		//     }
		//   },

		onNavigationBarButtonTap(e) {
			console.log(e, 333);
			this.showBars()

		},

		methods: {


			setTextSize(index) {
				this.index = index
				uni.setStorageSync('fontSizeIndex', index)
				setTimeout(() => {
					this.$refs.popupTextSize.close()
				}, 100)
			},

			// 点击文章中的图片
			articleClick(val) {
				this.$refs.imagePreview.init(val.target.src)
			},

			imgClose() {
				this.$refs.popupImg.close()
			},

			//手指触摸动作开始
			touchstart(item) {
				this.timer = setTimeout(() => {
					this.handleData = item
					this.$refs.tapLongPopupRef.init()
					this.pageData.chapterList.forEach((row) => {
						row.checked = 0
					})
					item.checked = 1
					console.log(item, 11)
				}, 1000)
			},



			//手指触摸动作结束
			touchend() {
				//延时执行为了防止 click() 还未判断 islongPress 的值就被置为 fasle
				clearTimeout(this.timer);
				setTimeout(() => {
					// this.islongPress = false
				}, 200)
			},

			hideNav() {
				// this.$refs.navBarPopupRef.navClose()
				let vm = this
				// uni.navigateTo({
				// 	url: `/pages/detail/detail?id=${vm.goodsId}&bookId=${vm.goodsId}&navShow=0`
				// });
				uni.navigateBack()
			},

			navClose() {
				// this.showMask = false
				this.hideNav()
			},

			navChange(val) {
				console.log(val, 111)

				let vm = this

				const query = uni.createSelectorQuery().in(this)
				query
					.select(val)
					.boundingClientRect((data) => {
						console.log(data, 'data')
						let pageScrollTop = Math.round(data.top)
						//   uni.pageScrollTo({
						//     scrollTop: pageScrollTop, //滚动的距离
						//     duration: 0, //过渡时间
						// })
						console.log(pageScrollTop, vm.scrollToped, 333)
						let h = 10
						/* #ifdef APP-PLUS */
						// h = 79
						/*#endif*/
						vm.scrollTop = vm.scrollToped + pageScrollTop - h
						console.log(vm.scrollTop, 444)
					})
					.exec()

				setTimeout(() => {
					uni.setStorageSync('detailScroll', '');
				}, 200)
			},

			showBars() {
				let vm = this
				// this.showMask = true
				// this.$refs.navBarPopupRef.init()



				if (vm.navShow == 0) {
					uni.navigateTo({
						url: `/pages/detail/detail?id=${vm.goodsId}&bookId=${vm.goodsId}&navShow=1`
					});
				}



			},

			loginSuccess() {
				window.location.reload()
			},

			goback() {
				uni.navigateBack({});
			},
			bindPickerChange(obj) {
				this.index = obj.detail.value
				uni.setStorageSync('fontSizeIndex', this.index)
			},
			onScroll(res) {
				// console.log(res)
				this.scrollToped = res.detail.scrollTop
			},
			// 点击下面得弹窗
			onTapLong(type) {
				let vm = this
				if (type == 1) {
					APIJS.bookmarkAdd({
						contentId: vm.goodsId,
						scrollInfo: vm.scrollToped
					}).then((res) => {
						uni.showToast({
							title: '加入书签成功！',
							duration: 2000,
							icon: 'success'
						});
						vm.bookId = res.data
						vm.content[2].active = true
					})
				} else if (type == 2) {
					console.log(this.handleData, 777)

					/*#ifdef H5*/
					// var divText = document.getElementById('itemId' + this.handleData.sort).innerText;
					/*#endif*/

					/* #ifdef APP-PLUS */
					/*#endif*/
					var divText = vm.removeLableAndImage(this.handleData.data);


					uni.setClipboardData({
						data: divText, //当前点击的地址
						success: () => {
							//获取刚复制好的地址到剪切板，
							uni.getClipboardData({
								success: () => {
									uni.showToast({
										title: '复制成功'
									})
								}
							});
						}
					});
				}

				this.pageData.chapterList.forEach((row) => {
					row.checked = 0
				})

			},

			onCancel() {
				this.pageData.chapterList.forEach((row) => {
					row.checked = 0
				})
			},

			removeLableAndImage(html) {
				let msg = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
					.replace(/<br\/?>/gi, '\n').replace(/<[^>/]+>/g, '')
					.replace(/(\n)?<\/([^>]+)>/g, '').replace(/\u00a0/g, ' ')
					.replace(/&nbsp;/g, ' ').replace(/<\/?(img)[^>]*>/gi, '')
					.replace(/&amp;/g, "&").replace(/&lt;/g, "<")
					.replace(/&gt;/g, ">")
					.replace(/&#39;/g, "\'")
					.replace(/&quot;/g, "\"")
					.replace(/<\/?.+?>/g, "")
				return msg
			},

			trigger(e) {
				let vm = this

				if (e.index == 1) {
					this.$refs.popupTextSize.open('center')
				}

				if (e.index == 0) {
					uni.navigateTo({
						url: '/pages/index/index'
					});
				}

				if (e.index == 2) {

					console.log(vm.bookId, 'vm.bookId')

					if (vm.content[e.index].active) {
						APIJS.delBookmark({
							id: vm.bookId,
						}).then((res) => {
							uni.showToast({
								title: '删除书签成功！',
								duration: 2000,
								icon: 'success'
							});
							vm.content[e.index].active = !e.item.active
							vm.content[e.index].text = '加入书签'
						}).catch((e) => {
							uni.hideLoading();
							setTimeout(() => {
								goLogin(`/pages/detail/detail?id=${vm.goodsId}`)
							}, 600)
						})
					} else {
						APIJS.bookmarkAdd({
							contentId: vm.goodsId,
							scrollInfo: vm.scrollToped
						}).then((res) => {
							uni.showToast({
								title: '加入书签成功！',
								duration: 2000,
								icon: 'success'
							});
							vm.bookId = res.data
							vm.content[e.index].active = !e.item.active
							vm.content[e.index].text = '删除书签'
						}).catch((e) => {
							uni.hideLoading();
							setTimeout(() => {
								goLogin(`/pages/detail/detail?id=${vm.goodsId}`)
							}, 600)
						})
					}
				}

			},
		}
	}
</script>
<style>

</style>
<style lang="less" scoped>
	.scrollWrap {
		position: relative;

		.mask {
			width: 100%;
			height: 100vh;
			position: absolute;
			left: 0;
			top: 0px;
			z-index: 999;
			background-color: rgba(0, 0, 0, 0.5);
		}
	}


	.pageBox {
		padding: 10px 10px;

		.title {

			color: #333;
			font-weight: bold;
			text-align: center;
		}

		.desc {

			color: #000;
			padding-top: 5px;
			line-height: 1.4em;


			padding-top: 10px;
			background-color: #f5f5f5;
			padding: 5px;
			border: 1px solid #ddd;
			margin-top: 10px;
			border-bottom: 1px solid #ddd;

			.item {
				display: flex;
				padding: 3px 0;

				.text1 {
					width: 6em;
					color: #999;
				}

				.text2 {
					flex: 1;
					color: #333;
				}

			}
		}

		.content {
			padding: 10px 0 100px;
			color: #333;
			line-height: 1.2em;

			.item {
				border-bottom: 1px solid #ddd;
				padding: 10px 0;

				&.active {
					background-color: #aee1f6;
				}
			}
		}
	}




	.pageBox2 {
		width: 100%;
		background-color: #fff;
		padding: 5px 15px;
		z-index: 9999;
		width: 400upx;


		.item {
			font-size: 14px;
			line-height: 40px;
			padding: 0 10px;
			color: #666;
			text-align: center;
			border-bottom: 1px solid #f5f5f5;

			&:last-child {
				border: 0;
			}

			&.active {
				color: rgb(18, 150, 219);
				background-color: #f5f5f5;
			}

			&:active {
				color: rgb(18, 150, 219);
				background-color: #f5f5f5;
			}
		}

	}
</style>